import json
import os
import subprocess

app_icons = json.load(open("app_icons.json"))


def main():
    active_work_id = (
        subprocess.run(
            ["aerospace", "list-workspaces", "--focused"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        .stdout.decode("utf-8")
        .strip()
    )

    current_work_name = os.environ["NAME"]  # space_icon, space_icon
    current_work_id = current_work_name.split("_")[1]

    is_current_work_focused = active_work_id == str(current_work_id)

    apps_lines = (
        subprocess.run(
            ["aerospace", "list-windows", "--workspace", str(current_work_id)],
            capture_output=True,
            text=True,
        )
        .stdout.strip()
        .split("\n")
    )

    def app_remap(app):
        return {
            "Cursor": "Code",
        }.get(app, app)

    apps = [
        app_remap(line.split("|")[1].strip()) for line in apps_lines if line
    ]
    apps_count = {app: apps.count(app) for app in apps}
    apps = set(apps)

    icon_line = ""
    for app in apps:
        icon = app_icons.get(app, ":default:")
        if apps_count[app] > 1:
            icon = icon * apps_count[app]
        icon_line += icon

    subprocess.run(
        [
            "sketchybar",
            "-m",
            "--set",
            current_work_name,
            "label=" + (icon_line or "-"),
            "icon.highlight=" + str(is_current_work_focused).lower(),
            "label.highlight=" + str(is_current_work_focused).lower(),
        ]
    )
